package userwash

import (
	"context"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/userwash"
	"gorm.io/gorm"
	"time"
)

type UserWashModel struct {
	ctx context.Context
	db  *gorm.DB
}

func (m *UserWashModel) GetDB() *gorm.DB {
	return m.db
}

func NewUserWashModel(ctx context.Context, db *gorm.DB) *UserWashModel {
	return &UserWashModel{
		ctx: ctx,
		db:  db,
	}
}

func (m *UserWashModel) GetTodayWash(userId int64, typeName string) (float64, error) {
	currentTime := time.Now()
	// 　使用time.Date方法构造当前时间的日期时间（重置　时　分　秒都为０）
	zeroTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(),
		0, 0, 0, 0, currentTime.Location()).Unix()
	tx := m.db.WithContext(m.ctx).Model(&userwash.UserWash{}).Select("sum(value) as value").Where("user_id = ?", userId).
		Where("created_at > ?", zeroTime)
	if typeName != "" {
		tx.Where("type_name = ?", typeName)
	}
	var total Total
	return total.Value, tx.First(&total).Error
}

func (m *UserWashModel) GetTotalWash(userId int64, typeName string) (float64, error) {
	tx := m.db.WithContext(m.ctx).Model(&userwash.UserWash{}).Select("sum(value) as value").Where("user_id = ?", userId)
	if typeName != "" {
		tx.Where("type_name = ?", typeName)
	}
	var total Total
	return total.Value, tx.First(&total).Error
}

func (m *UserWashModel) AddUserWash(userWash *userwash.UserWash) error {
	return m.db.WithContext(m.ctx).Model(&userwash.UserWash{}).Create(userWash).Error
}

func (m *UserWashModel) ListUserWash(userId int64, typeName string, page, pageSize int64) ([]*userwash.UserWash, int64, error) {
	tx := m.db.WithContext(m.ctx).Model(&userwash.UserWash{})
	if userId != 0 {
		tx.Where("user_id = ?", userId)
	}
	if typeName != "" {
		tx.Where("type_name = ?", typeName)
	}

	// 数据条数
	var total int64
	if err := tx.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	var userWashes []*userwash.UserWash
	if err := tx.Order("created_at desc").Offset(int((page - 1) * pageSize)).Limit(int(pageSize)).
		Find(&userWashes).Error; err != nil {
		return nil, 0, err
	}
	return userWashes, total, nil
}
